<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/8
 * Time: 17:37
 */

namespace App\Rep;


use App\Jobs\BatchAddJobTypePrice;
use App\Models\ModelNumber;
use App\Models\ModelNumberSpecification;
use App\Models\Order;
use App\Models\OrderChild;
use App\Models\Product;
use App\Models\ProductCenter;
use App\Models\ProductJobType;
use App\Models\ProductModelNumber;
use App\Models\Specification;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class SpecificationRep
{

    /**
     * 获取规格列表
     * @param $params
     * @return mixed
     */
    public function getSpecificationListRep($params){
//        $list = Specification::Search($params)
//            ->orderBy('id','desc')
//            ->paginate($params['per_page']??20);

        if(isset($params['model_number_id']) && !empty($params['model_number_id'])){
            $ids = ModelNumberSpecification::where('product_id',$params['product_id'])->where('model_number_id',$params['model_number_id'])->pluck('specification_id');
            $list = Specification::whereIn('id',$ids)
                ->where('is_del',2)
                ->orderBy('id','desc')
                ->paginate($params['per_page']??1000);
        }else{
            $list = Specification::Search($params)
                ->where('is_del',2)
                ->orderBy('id','desc')
                ->paginate($params['per_page']??1000);
        }

        return $list;
    }

    /**
     * 添加规格，关联规格
     * @param $params
     * @return Specification|array
     */
//    public function createSpecificationRep($params){
//        $ids = [];
//        if(!empty($params['specification_ids'])){
//            foreach($params['specification_ids'] as $k=>$v){
//                $obj = Specification::updateOrCreate(['specification'=>$v],['specification'=>$v,'is_del'=>2]);
//                $where = ['product_id'=>$params['product_id'],'specification_id'=>$obj->id,'model_number_id'=>$params['model_number_id']];
//                ModelNumberSpecification::updateOrCreate($where,$where);
//                //ProductCenter::updateOrCreate($where,$where);
//                $product_job_type = ProductJobType::where('product_id',$params['product_id'])->get();
//                foreach($product_job_type as $kk=>$vv){
//                    ProductCenter::updateOrCreate(
//                        [
//                            'product_id'=>$params['product_id'],
//                            'specification_id'=>$obj->id,
//                            'model_number_id'=>$params['model_number_id'],
//                            'job_type_id'=>$vv->job_type_id
//                        ],
//                        [
//                            'product_id'=>$params['product_id'],
//                            'specification_id'=>$obj->id,
//                            'model_number_id'=>$params['model_number_id'],
//                            'job_type_id'=>$vv->job_type_id
//                        ]);
//                }
//                $ids[] = $obj->id;
//            }
//        }
//        return ['code'=>0,'data'=>$ids,'msg'=>'success'];
//    }

    /**
     * 编辑规格
     */
//    public function updateSpecificationRep($params){
//        $model = Specification::where('id',$params['id'])->first();
//        $model->specification = $params['specification'];
//        $model->save();
//        return $model;
//    }


    public function addSpecificationRep($params){
        if(!empty($params['id'])){
            $model = Specification::where('id',$params['id'])->first();
            $model->specification = $params['specification'];
            $model->image = $params['image'];
            $model->save();
        }else{
            $model = Specification::updateOrCreate(
                ['specification'=>$params['specification']],
                ['specification'=>$params['specification'],'image'=>$params['image'],'is_del'=>2]
            );
        }
        return $model;
    }

    public function deleteSpecificationRep($params){
        $model = Specification::where('id',$params['id'])->first();
        $model->is_del =1;
        $model->save();
//        $where = ['specification_id'=>$params['id']];
//        ModelNumberSpecification::where($where)->delete();
        //ProductCenter::where('')
        return true;
    }

    /**
     * 删除规格关联
     * @param $params
     */
//    public function delSpecificationRep($params){
////        $model = Specification::where('id',$params['specification_id'])->first();
////        $model->is_del =1;
////        $model->save();
//        $where = ['product_id'=>$params['product_id'],'specification_id'=>$params['specification_id'],'model_number_id'=>$params['model_number_id']];
//        ModelNumberSpecification::where($where)->delete();
//        return true;
//    }

    /**
     * 设置工种价格
     * @param $params
     */
    public function setJobTypePriceBySpecificationIdRep($params){
        //$job_type_price_arr = json_decode($params['job_type_price_arr'][0],true);
        $params['is_update'] = $params['is_update']??1;
        $job_type_price_arr = $params['job_type_price_arr'];
        if($params['product_id'] == 1){
            $params['specification_id'] = null;
        }
        foreach($job_type_price_arr as $k=>$v){
            $v=json_decode($v,true);
            $where = [
                'product_id'=>$params['product_id'],
                'model_number_id'=>$params['model_number_id'],
                'specification_id'=>$params['specification_id'],
                'job_type_id'=>$v['job_type_id']
            ];
            ProductCenter::updateOrCreate($where,[$where,'price'=>$v['price'],'remark'=>$v['remark']??'工艺备注默认值']);
            if($params['is_update'] == 1){
                $ids = Order::where('product_id',$params['product_id'])
                    ->where('model_number_id',$params['model_number_id'])
                    ->where(function($q)use($params){
                        if($params['product_id'] == 1){
                            $params['specification_id'] = null;
                        }
                        $q->where('specification_id',$params['specification_id']);
                    })
                    ->where('is_del',2)
                    ->pluck('id')->toArray();
                //同步子订单工价
                OrderChild::whereIn('order_id',$ids)
                    ->where('is_del',2)
                    ->where('job_type_id',$v['job_type_id'])
                    ->update(['price'=>$v['price']]);
            }
        }
        return true;
    }

    /**
     * 获取规格工种及价格
     * @param $params
     */
    public function getJobTypePriceBySpecificationIdRep($params){
        $model = ProductCenter::query();
        $model->where('product_id',$params['product_id']);
        $model->where('model_number_id',$params['model_number_id']);
        if($params['product_id'] == 1){
            $params['specification_id'] = null;
        }
        $model->where('specification_id',$params['specification_id']);
        $data = $model->with(['job_type'])->get();
        return $data;
    }

    /**
     * 获取相同工序的产品列表
     */
    public function getSameJobTypeListProductListRep($params){
        $product_id = $params['product_id'];
        $list = ProductJobType::where('product_id',$product_id)->orderBy('job_type_id','asc')->pluck('job_type_id')->toArray();
        $job_type_str = implode(',',$list);
        //p($job_type_str);
        $product_id_list = ProductJobType::select('product_id',DB::raw('group_concat(job_type_id order by job_type_id asc) as job_type_list'))
            //->where('product_id','<>',$product_id)
            ->groupBy('product_id')
            ->having('job_type_list',$job_type_str)
            ->pluck('product_id')->toArray();
        //p($product_id_list);
        return Product::whereIn('id',$product_id_list)->select('id','product_name')->get();
    }


    /**
     * 批量设置工种价格
     * @param $params
     */
    public function batchSetJobTypePriceRep($params){
        $old = ProductCenter::where('product_id',$params['old_product_id'])
            ->where('model_number_id',$params['old_model_number_id'])
            ->where('specification_id',$params['old_specification_id'])
            ->get();
        $product_ids = $params['product_ids'];
        $model_number_ids = $params['model_number_ids'];
        $specification_ids = $params['specification_ids'];
        if(count($product_ids)>1){
            foreach($old as $k=>$v){
                foreach($product_ids as $vv){
                    ProductCenter::where('product_id',$vv)
                        ->where('job_type_id',$v->job_type_id)
                        ->update(['price'=>$v->price]);
                }
            }
        }else{
            if(count($model_number_ids)>1){
                foreach($old as $k=>$v){
                    foreach($model_number_ids as $vv){
                        ProductCenter::where('product_id',$product_ids[0])
                            ->where('model_number_id',$vv)
                            ->where('job_type_id',$v->job_type_id)
                            ->update(['price'=>$v->price]);
                    }
                }
            }else{
                if(count($specification_ids)>1){
                    foreach($old as $k=>$v){
                        foreach($specification_ids as $vv){
                            ProductCenter::where('product_id',$product_ids[0])
                                ->where('model_number_id',$model_number_ids[0])
                                ->where('specification_id',$vv)
                                ->where('job_type_id',$v->job_type_id)
                                ->update(['price'=>$v->price]);
                        }
                    }
                }else{
                    foreach($old as $k=>$v){
                        ProductCenter::where('product_id',$product_ids[0])
                            ->where('model_number_id',$model_number_ids[0])
                            ->where('specification_id',$specification_ids[0])
                            ->where('job_type_id',$v->job_type_id)
                            ->update(['price'=>$v->price]);
                    }
                }
            }
        }
        return true;
    }

    /**
     * 添加规格图片
     * @param $params
     * @return void
     */
    public function addSpecificationImageRep($params){
        return ModelNumberSpecification::updateOrCreate(
            [
                'product_id'=>$params['product_id'],
                'model_number_id'=>$params['model_number_id'],
                'specification_id'=>$params['specification_id']
            ],[
                'product_id'=>$params['product_id'],
                'model_number_id'=>$params['model_number_id'],
                'specification_id'=>$params['specification_id'],
                'image'=>$params['file_url']
            ]
        );
    }

    /**
     * 获取规格图片
     * @param $params
     * @return void
     */
    public function getSpecificationImageRep($params){
        $where = [
            'product_id'=>$params['product_id'],
            'model_number_id'=>$params['model_number_id'],
            'specification_id'=>$params['specification_id']
        ];
        return ModelNumberSpecification::where($where)->first();
    }

    /**
     * 批量添加工价
     * @param $params
     * @return bool
     */
    public function batchAddJobTypePriceRep($params){
        // 异步写入，提高操作流畅性
        $job = (new BatchAddJobTypePrice($params));
        dispatch($job);
        Artisan::call('queue:work', [
            '--queue' => 'batchAddJobTypePrice'
        ]);
        return true;
    }
}
